package com.small.account.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.small.account.entity.AuPermission;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;
import java.util.Set;

/**

 * Mapper 接口

 *
 * @author wangguochao
 * @since 2020-01-06
 */
public interface AuPermissionMapper extends BaseMapper<AuPermission> {

    /**
     * user权限
     */
    @Select("SELECT  " +
            " _ap.*  " +
            "FROM  " +
            " au_user _au  " +
            " JOIN user_and_role _uar ON _au.id = _uar.user_id  " +
            " JOIN au_role _ar ON _ar.id = _uar.role_id  " +
            " JOIN permission_and_role _rap ON _ar.id = _rap.role_id  " +
            " JOIN au_permission _ap ON _rap.permission = _ap.id  " +
            "WHERE  " +
            " _au.user_name =  #{userName}")
    List<AuPermission> findTreeByUserName(@Param("userName")String userName);

    /**
     * 用户角色
     */
    @Select("SELECT _ap.* FROM au_role _ar JOIN permission_and_role _rap ON _ar.id = _rap.role_id JOIN au_permission _ap ON _ap.permission_code = _rap.permission WHERE _ar.id = #{roleId}")
    List<AuPermission> getRolePermission(String roleId);

    @Select("SELECT DISTINCTROW ap.*  FROM app_user au JOIN user_and_role uar ON au.id = uar.user_id JOIN permission_and_role par ON par.role_id = uar.role_id JOIN au_permission ap ON ap.permission_code = par.permission WHERE au.id = #{id}")
    List<AuPermission> findByPermission(@Param("id") String id);

    @Select("SELECT " +
            "DISTINCT _ap.permission_code  " +
            "FROM " +
            "user_and_role _uar  " +
            "JOIN au_role _ar ON _ar.id = _uar.role_id " +
            "JOIN permission_and_role _rap ON _ar.id = _rap.role_id " +
            "JOIN au_permission _ap ON _rap.permission = _ap.permission_code  " +
            "WHERE " +
            "_uar.user_id = #{id} " +
            "AND _ap.permission_groups = 'RESOURCES'")
    List<String> findPermissionById(String id);

    @Select("SELECT " +
            " au.id  " +
            "FROM " +
            " app_user au " +
            " JOIN user_and_role uar ON au.id = uar.user_id " +
            " JOIN permission_and_role par ON uar.role_id = par.role_id " +
            " WHERE au.dept_id = #{deptId} AND par.permission = #{permissionCode}")
    List<String> getUsersByPermissionCodeAndDeptId(String permissionCode, String deptId);

}
